<template>
  <view :style="{ height: windowHeight + 'px' }" class="camear-wrapper" v-if="visible">
    <cover-view class="controls-top" :style="{ width: '100%', height: layerHeight + 'px' }"></cover-view>
    <cover-view class="controls-down" :style="{
          width: '100%',
          top: layerTop + 'px',
          height: layerBottomHeight + 'px',
        }"></cover-view>
    <camera mode="normal" device-position="back" flash="off" :style="{ height: cameraHeight + 'px' }">
      <!-- 头像面 -->
      <view class="id-card-text"> 身份证人像面 </view>
      <cover-image id="id-card-wrapper" class="id-card-wrapper" :src="baseImgUrl + 'id-card-wrapper.png'" />

      <view class="example-tips">
        将身份证<span class="red-text">人像面</span>置入此区域内（尝试边缘对齐）
      </view>
      <image :src="baseImgUrl +'id-card-example.png'" class="id-card-example"></image>
    </camera>
    <view class="bottom font-36-fff" ref="bottomRef" id="bottom-container">
      <view class="wrap">
        <view class="back" @click="hideCamera">
          <image :src="baseImgUrl +'/back.png'" class="back-img"></image>
        </view>
        <view @click="takePhoto" class="take-photo-button"> </view>
        <view @click="chooseImage" class="import-album-wrapper">
          <image :src="baseImgUrl +'/album.png'" class="import-img"></image>
          <view class="import-text">导入图片</view>
        </view>
      </view>
    </view>
    <canvas canvas-id="myCanvas"
      :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px',position: 'fixed',top: `${canvasTop}` }"
      @error="error"></canvas>
  </view>
</template>

<script>
  import {
    base64ToImage,
    getBase64Two,
    Toast
  } from '@/utils/util.js'
  export default {
    name: 'YyPhotoMask',
    props: {
      baseImgUrl: {
        type: String,
        default: ''
      },
      visible: {
        type: Boolean,
        default: false
      },
      clientId: {
        type: String,
        default: ''
      },
      clientSecret: {
        type: String,
        default: ''
      },
      // 识别类型
      // idCard 身份证
      // licensePlate  车牌
      identifyType: {
        type: String,
        default: 'idCard'
      }
    },
    data() {
      return {
        canvasWidth: 0,
        canvasHeight: 0,
        layerHeight: 0,
        layerTop: 0,
        layerBottomHeight: 0,
        windowHeight: "",
        cameraHeight: "",
        cameraContext: {},
        systemInfo: null,
        croppingX: 0,
        croppingY: 0,
        croppingWidth: 0,
        croppingHeight: 0,
        canvasTop: -99999
      }
    },
    watch: {
      visible(newVal, oldVal) {
        if (newVal) {
          this.initMaskPosition()
        }
      }
    },
    mounted() {
      const systemInfo = uni.getSystemInfoSync();
      this.systemInfo = systemInfo;
      if (uni.createCameraContext) {
        this.cameraContext = uni.createCameraContext();
      } else {
        // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
        uni.showModal({
          title: "提示",
          content: "当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。",
        });
      }
    },
    methods: {
      // 初始化，蒙版位置
      initMaskPosition() {
        this.$nextTick(() => {
          uni
            .createSelectorQuery()
            .in(this)
            .select("#id-card-wrapper")
            .boundingClientRect((res) => {
              console.log(res, 'res')
              this.layerHeight = res.top;
              this.layerTop = res.bottom;
              // 保存要裁剪的位置
              this.croppingX = 0
              this.croppingY = res.top
              this.croppingWidth = res.width
              this.croppingHeight = res.height
              uni
                .createSelectorQuery()
                .in(this)
                .select("#bottom-container")
                .boundingClientRect((resBottom) => {
                  this.windowHeight = this.systemInfo.windowHeight;
                  this.cameraHeight =
                    this.systemInfo.windowHeight - resBottom.height;
                  this.layerBottomHeight =
                    this.systemInfo.windowHeight - res.bottom - resBottom.height;
                })
                .exec();
            })
            .exec();
        });
      },
      takePhoto() {
        uni.showLoading({
          title: "拍摄中",
        });
        this.cameraContext.takePhoto({
          quality: "normal",
          success: (res) => {
            this.afterRead(res);
            this.$emit('update:visible', false)
            uni.showToast({
              title: "拍照成功",
              icon: "none",
              duration: 1200,
            });
          },
          fail: (err) => {
            uni.showToast({
              title: "拍照失败，请检查系统是否授权",
              icon: "none",
              duration: 1200,
            });
          },
          complete: () => {
            uni.hideLoading()
          }
        });
      },
      afterRead(info) {
        let _this = this;
        uni.request({
          url: "https://aip.baidubce.com/oauth/2.0/token",
          method: "GET",
          data: {
            grant_type: "client_credentials",
            client_id: _this.clientId,
            client_secret: _this.clientSecret,
          },
          success(res) {
            _this.base64Handle(res.data.access_token, info);
          },
        });
      },
      base64Handle(token, info) {
        getBase64Two(info.tempImagePath)
          .then((res) => {
            return res;
          })
          .then((res) => {
            // 如果识别的类型是身份证
            if (this.identifyType === 'idCard') {
              this.identifyIdCard(res, token)
            }
            if (this.identifyType === 'licensePlate') {
              this.identifyLicensePlate(res, token)
            }
          });
      },
      drapImgLast(info, yingNum) {
        let _this = this;
        const ctx = uni.createCanvasContext("myCanvas", _this);

        uni.getImageInfo({
          src: info.tempImagePath,
          success(res1) {
            console.log(res1, 'res1', yingNum)
            let {
              width,
              height,
              path
            } = res1;
            if (yingNum == 90) {
              _this.canvasWidth = height;
              _this.canvasHeight = width;
              ctx.clearRect(0, 0, width, width); // 清空画布

              ctx.translate(_this.canvasWidth, 0);
              ctx.rotate((yingNum * Math.PI) / 180);
            } else if (yingNum == 270) {
              _this.canvasWidth = height;
              _this.canvasHeight = width;
              ctx.clearRect(0, 0, height, width); // 清空画布

              ctx.translate(0, _this.canvasHeight - 10);
              ctx.rotate((yingNum * Math.PI) / 180);
            } else if (yingNum == 180) {
              _this.canvasWidth = width;
              _this.canvasHeight = height;
              ctx.clearRect(0, 0, width, height); // 清空画布

              ctx.translate(_this.canvasWidth, _this.canvasHeight);
              ctx.rotate((-yingNum * Math.PI) / 180);
            } else {
              // 清空画布
              _this.canvasWidth = width
              _this.canvasHeight = height
              ctx.clearRect(0, 0, width, height);
            }
            ctx.drawImage(path, 0, 0);
            // let x = 10;
            // let y = 100;
            // let imageWidth = 
            // let imageHeight = 100
            // 将生成的canvas图片，转为真实图片， 并进行裁剪
            this.canvasTop = 200
            ctx.draw(false, () => {
              setTimeout(() => {
                console.log('绘制完成')
                uni.canvasToTempFilePath({
                  canvasId: "myCanvas",
                  // x: _this.croppingX,
                  // y: _this.croppingY,
                  // width: _this.croppingWidth,
                  // height: _this.croppingHeight,
                  // destWidth: _this.croppingWidth,
                  // destHeight: _this.croppingHeight,
                  x: 100,
                  y: 200,
                  width: 50,
                  height: 50,
                  destWidth: 100,
                  destHeight: 100,
                  success(res2) {
                    console.log(res2, 'res2')
                    _this.$emit('generateFilePath', res2.tempFilePath)
                  },
                  fail() {}
                }, _this);
              }, 1000);
            });
          },
        });
      },
      hideCamera() {
        this.$emit('update:visible', false)
      },
      chooseImage() {
        uni.chooseImage({
          count: 1,
          sizeType: ["original", "compressed"],
          sourceType: ["album"],
          success: (res) => {
            this.afterRead({
              tempImagePath: res.tempFilePaths[0]
            })
            this.$emit('update:visible', false)
          },
          fail: (err) => {},
        });
      },
      identifyIdCard(res, token) {
        uni.request({
          url: `https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=${token}`,
          method: "POST",
          header: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
          data: {
            id_card_side: "front",
            image: res,
            detect_direction: true,
            detect_card: true
          },
          success: (resbai) => {
            let {
              statusCode,
              data
            } = resbai;

            if (statusCode == 200 && data.words_result["姓名"]) {
              this.$emit('parsedSuccess', {
                userName: data.words_result.姓名.words,
                idcard: data.words_result.公民身份号码.words,
                domicileAddress: data.words_result.住址.words,
                nation: data.words_result.民族.words,
                words_result: data.words_result
              })
              // 图片旋转  start
              var yingNum = 0;
              var direction = data.direction;
              if (direction != -1 && direction != 0) {
                if (direction == 1) {
                  //逆时针90°
                  yingNum = 90;
                } else if (direction == 2) {
                  //逆时针180°
                  yingNum = 180;
                } else if (direction == 3) {
                  //逆时针270°
                  yingNum = 270;
                }
              }
              // 取 百度裁剪图片的结果返回
              base64ToImage(`data:image/png;base64,${data.card_image}`)
                .then((res) => {
                  this.$emit('generateFilePath', res)
                })
            } else {
              Toast("未识别出身份证信息，请重试！");
            }
          },
        });
      },
      identifyLicensePlate(res, token) {
        uni.request({
          url: `https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate?access_token=${token}`,
          method: "POST",
          header: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
          data: {
            image: res
          },
          success: (resbai) => {
            let {
              statusCode,
              data
            } = resbai;
            console.log(resbai)
            if (statusCode == 200 && data.words_result["姓名"]) {
              // _this.$emit('parsedSuccess', {
              //   userName: data.words_result.姓名.words,
              //   idcard: data.words_result.公民身份号码.words,
              //   domicileAddress: data.words_result.住址.words,
              //   nation: data.words_result.民族.words,
              //   words_result: data.words_result
              // })
            } else {
              Toast("未识别出车牌信息，请重试！");
            }
          },
        });
      }
    }
  }
</script>

<style lang="scss" scoped>
  .camear-wrapper {
    height: 100%;
    position: relative;

    .icon-w569-h828 {
      width: 569rpx;
      height: 828rpx;
    }

    .controls-top {
      background: #000000;
      opacity: 0.5;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 1;
      height: 270rpx;
    }

    .controls-down {
      background: #000000;
      opacity: 0.5;
      position: absolute;
      top: 718rpx;
      left: 0;
      z-index: 1;
    }

    .id-card-wrapper {
      width: 100%;
      height: 448rpx;
      margin: 0 auto;
    }

    .example-tips {
      font-size: 24rpx;
      color: #ffffff;
      text-align: center;
      margin-top: 40rpx;
      margin-bottom: 53rpx;
      font-weight: 400;

      .red-text {
        color: #ff0208;
      }
    }

    .id-card-text {
      font-size: 36rpx;
      top: 48rpx;
      color: #ffffff;
      width: 296rpx;
      height: 72rpx;
      border-radius: 36rpx;
      border: 1px solid #f3f3f3;
      display: flex;
      align-items: center;
      margin: 0 auto;
      margin-top: 48rpx;
      margin-bottom: 60rpx;
      font-weight: 500;
      justify-content: center;
    }

    .id-card-example {
      width: 240rpx;
      height: 152rpx;
      margin: 0 auto;
      display: block;
      margin-bottom: 265rpx;
    }

    .bottom {
      width: 100%;
      background-color: #000;
      position: fixed;
      left: 0;
      bottom: 0;
      z-index: 999;

      .wrap {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 220rpx;
        padding: 0 73rpx;
      }

      .take-photo-button {
        width: 134rpx;
        height: 134rpx;
        border-radius: 50%;
        border: 7px solid #05ccfe;
        position: relative;

        &::after {
          content: "";
          width: 98rpx;
          height: 98rpx;
          background: #ffffff;
          border-radius: 50%;
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
        }
      }

      .back {
        width: 80rpx;
        height: 76rpx;
        padding: 20rpx;

        .back-img {
          width: 100%;
          height: 100%;
        }
      }

      .import-album-wrapper {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        .import-img {
          width: 49rpx;
          height: 42rpx;
          margin-bottom: 14rpx;
        }

        .import-text {
          font-weight: 500;
          font-size: 22rpx;
          color: #ffffff;
        }
      }
    }

    .w131-h131 {
      width: 131rpx;
      height: 131rpx;
    }

    .font-36-fff {
      font-size: 36rpx;
      color: #fff;
    }
  }
</style>